<template>
  <div class="login-container">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <el-icon class="back-icon" @click="goBack"><ArrowLeft /></el-icon>
      <div class="page-title">{{ t('login.title') }}</div>
      <div class="placeholder"></div>
    </div>

    <!-- 主体内容 -->
    <div class="login-content">
      <!-- 品牌标识 -->
      <div class="brand-logo">
        <h1>新一贷</h1>
        <div class="brand-slogan">30秒审批 | 实时到账 | 最长3年</div>
      </div>

      <!-- 登录表单区域 -->
      <div class="login-form-container">
        <!-- 手机号输入框 -->
        <div class="form-item" :class="{ 'error': errors.username }">
          <el-icon><Iphone /></el-icon>
          <input
            v-model="loginForm.username"
            :placeholder="t('login.phonePlaceholder')"
            class="form-input"
            type="text"
            @blur="validateField('username')"
            @input="clearError('username')"
          />
        </div>
        <div v-if="errors.username" class="error-message">{{ errors.username }}</div>

        <!-- 密码输入框 -->
        <div class="form-item" :class="{ 'error': errors.password }">
          <el-icon><Lock /></el-icon>
          <input
            v-model="loginForm.password"
            type="password"
            :placeholder="t('login.passwordPlaceholder')"
            class="form-input"
            @blur="validateField('password')"
            @input="clearError('password')"
          />
        </div>
        <div v-if="errors.password" class="error-message">{{ errors.password }}</div>

        <!-- 图形验证码 -->
        <div class="form-item" :class="{ 'error': errors.captcha }">
          <el-icon><Picture /></el-icon>
          <div class="captcha-container">
            <input
              v-model="loginForm.captcha"
              :placeholder="t('login.captchaPlaceholder')"
              class="form-input"
              @blur="validateField('captcha')"
              @input="clearError('captcha')"
            />
            <div class="image-captcha" @click="refreshCaptcha">
              <img :src="captchaImage" alt="验证码" />
            </div>
          </div>
        </div>
        <div v-if="errors.captcha" class="error-message">{{ errors.captcha }}</div>

        <!-- 登录按钮 -->
        <button
          type="button"
          class="login-button"
          :disabled="loading || hasErrors"
          @click="handleLogin"
        >
          {{ loading ? '登录中...' : t('login.loginButton') }}
        </button>

        <!-- 注册按钮 -->
        <button
          type="button"
          class="register-button"
          @click="goToRegister"
        >
          {{ t('login.registerButton') }}
        </button>

        <!-- 底部链接区域 -->
        <div class="bottom-links">
          <div class="forgot-password">
            <router-link to="/forgot-password">
              {{ t('login.forgotPassword') }}
            </router-link>
          </div>

          <div class="app-download">
            <span>APP下载</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useUserStore, useCaptchaStore } from 'store';
import { ElMessage } from 'element-plus';
import { ArrowLeft, Lock, Iphone, Picture } from '@element-plus/icons-vue';
import authService from '../../services/authService';

// 国际化
const { t } = useI18n();

// 路由
const router = useRouter();
const route = useRoute();

// Store
const captchaStore = useCaptchaStore();

// 表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
});

// 错误信息
const errors = reactive({
  username: '',
  password: '',
  captcha: ''
});

// 计算属性：是否有错误
const hasErrors = computed(() => {
  return Object.values(errors).some(error => error !== '');
});

// 加载状态
const loading = ref(false);

// 验证码图片
const captchaImage = ref('');

// 生命周期钩子
onMounted(() => {
  refreshCaptcha();
});

// 刷新验证码
const refreshCaptcha = () => {
  captchaImage.value = captchaStore.generateImageCaptcha();
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 跳转到注册页
const goToRegister = () => {
  router.push('/register');
};

// 清除特定字段的错误
const clearError = (field) => {
  errors[field] = '';
};

// 验证特定字段
const validateField = (field) => {
  switch (field) {
    case 'username':
      validateUsername();
      break;
    case 'password':
      validatePassword();
      break;
    case 'captcha':
      validateCaptcha();
      break;
  }
};

// 验证所有字段
const validateAllFields = () => {
  validateUsername();
  validatePassword();
  validateCaptcha();
  
  return !hasErrors.value;
};

// 验证手机号
const validateUsername = () => {
  if (!loginForm.username) {
    errors.username = t('login.phoneRequired');
    return false;
  }
  if (!/^1[3-9]\d{9}$/.test(loginForm.username)) {
    errors.username = t('login.phoneFormat');
    return false;
  }
  errors.username = '';
  return true;
};

// 验证密码
const validatePassword = () => {
  if (!loginForm.password) {
    errors.password = t('login.passwordRequired');
    return false;
  }
  if (loginForm.password.length < 6 || loginForm.password.length > 20) {
    errors.password = t('login.passwordLength');
    return false;
  }
  errors.password = '';
  return true;
};

// 验证图形验证码
const validateCaptcha = () => {
  if (!loginForm.captcha) {
    errors.captcha = t('login.captchaRequired');
    return false;
  }
  
  if (!captchaStore.verifyImageCaptcha(loginForm.captcha)) {
    errors.captcha = t('login.captchaError');
    return false;
  }
  
  errors.captcha = '';
  return true;
};

// 登录处理
const handleLogin = async () => {
  loading.value = true;
  // 表单验证
  if (!validateAllFields()) {
    return;
  }
  try {
    authService.login(loginForm);
    router.push('/');
  } catch (error) {
    // 登录失败，刷新验证码并清空表单数据
    refreshCaptcha();
    loginForm.captcha = '';
    clearError('captcha');
  } finally {
    loading.value = false;
  }
};
</script>



<style scoped lang="scss">
.login-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  background-color: #f5f7fa;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 15px;
  background-color: #3a4a6d;
  color: white;
  position: relative;
  width: 100%;

  .back-icon {
    font-size: 20px;
    cursor: pointer;
  }

  .page-title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    font-size: 18px;
    font-weight: 500;
  }

  .placeholder {
    width: 20px;
  }
}

.login-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
  width: 100%;
}

.brand-logo {
  text-align: center;
  margin: 0;
  color: #fff;
  background-color: #1e2a47;
  padding: 30px 0;
  width: 100%;

  h1 {
    font-size: 28px;
    margin-bottom: 10px;
    margin-top: 0;
  }

  .brand-slogan {
    font-size: 14px;
    color: #ccc;
    margin: 0;
  }
}

.login-form-container {
  padding: 20px;
  margin-top: 0;
  width: 100%;
}

.form-item {
  display: flex;
  align-items: center;
  background-color: white;
  border-radius: 4px;
  margin-bottom: 5px;
  padding: 0 15px;
  height: 50px;
  width: 100%;
  border: 1px solid transparent;
  transition: all 0.3s;

  &.error {
    border-color: #f56c6c;
  }

  .el-icon {
    margin-right: 10px;
    color: #999;
  }

  .form-input {
    flex: 1;
    border: none;
    outline: none;
    height: 100%;
    width: 100%;
    font-size: 16px;
    background: transparent;
  }
  
  .captcha-container {
    display: flex;
    flex: 1;
    align-items: center;
    
    .form-input {
      flex: 1;
    }
    
    .image-captcha {
      width: 100px;
      height: 36px;
      margin-left: 10px;
      cursor: pointer;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 4px;
      }
    }
  }
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin: -2px 0 10px 15px;
  height: 18px;
}

.login-button {
  width: 100%;
  height: 44px;
  margin-top: 20px;
  border-radius: 4px;
  font-size: 16px;
  background-color: #3a4a6d;
  border: none;
  color: white;
  cursor: pointer;

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

.register-button {
  width: 100%;
  height: 44px;
  margin-top: 15px;
  border-radius: 4px;
  font-size: 16px;
  background-color: white;
  color: #3a4a6d;
  border: 1px solid #3a4a6d;
  cursor: pointer;
}

.bottom-links {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  width: 100%;
}

.forgot-password {
  a {
    color: #666;
    text-decoration: none;
    font-size: 14px;
  }
}

.app-download {
  span {
    color: #666;
    font-size: 14px;
  }
}
</style>